﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Tools;

namespace PSCharts
{
    public class TaskPaneManager
    {
        const string mTitle = "PS Charts Add-In";
        
        readonly CustomTaskPaneCollection mPanes = Globals.ThisAddIn.CustomTaskPanes;
        readonly Application mApp = Globals.ThisAddIn.Application;
        readonly Dictionary<Presentation, CustomTaskPane> mPaneDictionary = new Dictionary<Presentation,CustomTaskPane>();

        TaskPaneManager()
        {
            HookUpEvents();
        }


        public void CreatePane<T>(Presentation pres) where T : System.Windows.Forms.UserControl, new()
        {
            CustomTaskPane pane = mPanes.Add(new T(), mTitle);
            mPaneDictionary.Add(pres, pane);
            pane.Visible = true;
        }

        public void DestroyPane(Presentation pres)
        {
            CustomTaskPane pane = mPaneDictionary[pres];
            mPanes.Remove(pane);
            mPaneDictionary.Remove(pres);
        }

        void HookUpEvents()
        {
            mApp.WindowActivate += mApp_WindowActivate;
            mApp.WindowDeactivate += mApp_WindowDeactivate;
            mApp.PresentationClose += mApp_PresentationClose;
        }

        void mApp_WindowActivate(Presentation Pres, DocumentWindow Wn)
        {
            SetPaneVisibility(Pres, true);
        }

        void mApp_WindowDeactivate(Presentation Pres, DocumentWindow Wn)
        {
            SetPaneVisibility(Pres, false);
        }

        void SetPaneVisibility(Presentation pres, bool visible)
        {
            CustomTaskPane pane;
            if (mPaneDictionary.TryGetValue(pres, out pane))
                pane.Visible = false;
        }

        void mApp_PresentationClose(Presentation Pres)
        {
            if (mPaneDictionary.ContainsKey(Pres))
                DestroyPane(Pres);
        }
    }
}
